<template>
  <div v-loading="loading" element-loading-text="模型生成中...">
    <div style="width: 280px; border: 1px solid white;">
      <el-form  ref="form" label-width="90px">
        <el-form-item label="模数">
          <el-input size="small" v-model.number="m" onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode== 46" type="number" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="头数">
          <el-input size="small" v-model.number="z1" onkeypress="return event.charCode >= 48 && event.charCode <= 57" type="number" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="压力角">
          <el-input size="small" v-model.number="alpha" onkeypress="return event.charCode >= 48 && event.charCode <= 57" type="number" placeholder="请输入内容">
            <i slot="suffix" style="font-style:normal; color: #606266;">°</i>
          </el-input>
        </el-form-item>
        <el-form-item label="齿顶高系数">
          <el-input size="small" v-model.number="Ha" onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode== 46" type="number" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="直径系数">
          <el-input size="small" v-model.number="q" onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode== 46" type="number" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="顶隙系数">
          <el-input size="small" v-model.number="C" onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode== 46" type="number" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="长度">
          <el-input size="small" v-model.number="b1" onkeypress="return event.charCode >= 48 && event.charCode <= 57" type="number" placeholder="请输入内容">
            <i slot="suffix" style="font-style:normal; color: #606266;">mm</i>
          </el-input>
        </el-form-item>
      </el-form>
      <div>
        <img src="/image/worm.png" height="200" width="280" />
        <div style="margin-top: 20px;text-align: center">
          <el-button type="primary" size="small" @click="creatWorm">确定</el-button>
          <el-button size="small" @click="closeDialog">取消</el-button>
        </div>
      </div>
    </div>


  </div>
</template>

<script>
  import {
    Axis,
    CrownCADPlugin,
    Direction, PluginCADToolFunctionType,
    PluginFunctionType,
    Point
  } from "../../../../nodeApp/static/lib/crowncad-plugin-sdk-0.0.1";
  export default {
    name: "Worm",
    data() {
      return {
        loading:false,
        m: 2.5,   // 模数
        z1: 1, //头数
        alpha: 20,   // 压力角
        pressureAngle:0,
        b1:60,  // 长度
        q: 11.2, // 直径系数
        Ha: 1, //齿顶高系数
        C:0.2, //顶隙系数
        ha2:0, //齿顶高
        hf2:0, //齿根高
        d1:0, //分度圆
        da1:0, //齿顶圆
        df1:0, //齿根圆
        px:0, //轴向齿槽宽
        Y:0, //导程角
        I:0, //导程
        crownCADPlugin: null,
        currentPickElement:null,
        planeFrontId:0 //前移基准面id
      }
    },
    mounted() {
      //创建插件对象
      this.crownCADPlugin = new CrownCADPlugin();
      //设置CrownCAD平台地址
      this.crownCADPlugin.setParentOrigin(window.url);
      //.设置与CrownCAD平台尝试建立连接的次数
      this.crownCADPlugin.setMaxAttempt(5);
      //设置插件在CrownCAD平台显示的尺寸
      this.crownCADPlugin.setLayout(315, 315, 550);
      //.发送与CrownCAD平台建立连接的请求

      this.crownCADPlugin.connect().then(() => {
        this.crownCADPlugin.request.execFunction(PluginFunctionType.LAYOUT, {minWidth: 300, width: 300, maxHeight: 595})
      });
    },
    methods: {
      closeDialog() {
        this.crownCADPlugin.request.execFunction(PluginCADToolFunctionType.CLOSEACTIVECMD, null);
      },

      //更新数据
      updateData() {
        this.pressureAngle = (this.alpha / 180) * Math.PI;
        this.d1 = this.m * this.q;
        this.ha2 = this.m * this.Ha;
        this.da1 = this.d1 + 2 * this.ha2;
        this.hf2 = this.m * this.Ha + this.C * this.m
        this.df1 = this.d1 - this.hf2 * 2
        this.px = Math.PI * this.m / 2
        this.Y = Math.atan(this.z1 * this.m / this.d1)
        this.I = this.m * this.z1 * Math.PI

	      //参数异常判断
        let j=  (0.5* (180 - 2* this.alpha) / 180) * Math.PI;
        let topLeftP= new Point(-1 * (this.I + 0.5 * this.b1 + 0.5 * this.px + (0.5* this.da1+ 1 - 0.5* this.d1)/Math.tan(j)),0.5* this.da1 + 1,0)
        let topRightP= new Point(-1* (this.I + 0.5 * this.b1- 0.5 * this.px-  (0.5* this.da1+ 1 - 0.5* this.d1)/Math.tan(j)),0.5* this.da1+ 1,0)
        let bottomLeftP= new Point(-1 * (this.I + 0.5 * this.b1 + 0.5 * this.px + (0.5* this.da1+ 1 - 0.5* this.d1)/Math.tan(j) - (0.5* this.da1+ 1 - 0.5* this.df1)/Math.tan(j)),0.5 * this.df1,0)
        let bottomRightP= new Point(-1* (this.I + 0.5 * this.b1- 0.5 * this.px-  (0.5* this.da1+ 1 - 0.5* this.d1)/Math.tan(j) + (0.5* this.da1+ 1 - 0.5* this.df1)/Math.tan(j)),0.5* this.df1,0)

	      let dis = Math.sqrt(Math.pow(topLeftP.x - topRightP.x, 2) + Math.pow(topLeftP.y - topRightP.y, 2))

	      if(bottomLeftP.x > bottomRightP.x || dis >= this.I) {
          let message = '请更改参数，如增大模数或头数，或减小压力角或齿顶高系数等'
          let msg = {type: 'warning', description: message}
          this.crownCADPlugin.event.messageTip(msg)
          return false
	      }
        return true
      },

      //创建蜗杆
      async creatWorm() {
        // 更新数据
        let status = this.updateData()
        if(!status) {
          return
        }

        this.loading= true

        //清空command
        this.crownCADPlugin.command.clearCommand();
        //创建草图，命名为草图1
        this.crownCADPlugin.command.sketch.createSketch({sketchName: '草图1', datumId: 8});

        // 齿顶圆
        this.crownCADPlugin.command.sketch.createCircle({
          centerPoint: new Point(0,0,0),
          circlePoint: new Point(0,0.5* this.da1,0),
        })

        //退出草图
        this.crownCADPlugin.command.sketch.exitSketch();
        //实现草图操作，参数true会覆盖之前的草图，不传则不会
        await this.crownCADPlugin.command.execute(true)

        //齿顶圆进行拉伸
        await this.createExtrude()

        //前移前视基准面获得‘前移基准面’
        await this.createPlane()

        //获取前移基准面的id
        let res = await this.crownCADPlugin.query.getEntitiesByFeatureNames(["前移基准面"]);
        this.planeFrontId= res.data.entities[0].id


        await this.crownCADPlugin.command.clearCommand();
        //在前移基准面绘制草图2
        this.crownCADPlugin.command.sketch.createSketch({sketchName: '草图2', datumId: this.planeFrontId});
        //绘制基圆，主包绘制螺旋曲线
        this.crownCADPlugin.command.sketch.createCircle({
          centerPoint: new Point(0,0,0),
          circlePoint: new Point(0,0.5* this.d1,0),
        })

        this.crownCADPlugin.command.sketch.exitSketch();
        //实现草图操作，参数true会覆盖之前的草图，不传则不会
        await this.crownCADPlugin.command.execute()
        this.crownCADPlugin.command.clearCommand();

        //根据草图2绘制螺旋曲线
        await this.createHelixCurve()

        //绘制封闭梯形为齿形
        await this.createTrapezoid()

        //根据齿形扫描切除
        await this.sweepCut()

        //清空command
        this.crownCADPlugin.command.clearCommand();
        //创建草图，命名为草图4
        this.crownCADPlugin.command.sketch.createSketch({sketchName: '草图4', datumId: 8});

        // 创建蜗杆轴的圆
        this.crownCADPlugin.command.sketch.createCircle({
          centerPoint: new Point(0,0,0),
          circlePoint: new Point(0,0.5* this.df1-2,0),
        })


        //退出草图
        this.crownCADPlugin.command.sketch.exitSketch();
        //实现草图操作，参数true会覆盖之前的草图，不传则不会
        await this.crownCADPlugin.command.execute()
        //拉伸草图4
        await this.createExtrude2()

        this.loading= false

      },

      //拉伸草图1
      createExtrude() {
        this.crownCADPlugin.command.clearCommand();
        return new Promise((resolve, reject) => {
          this.crownCADPlugin.query.getFeaturesByNames(["草图1"])
          // this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["草图1"]})
            .then(res => {
              if (res.code=== 200 && res.data.features.length) {
                this.crownCADPlugin.query.getEntitiesByFeatureIds([res.data.features[0]?.id])
              // this.crownCADPlugin.request.execFunction(PluginFunctionType.GETENTITIESBYFEATUREIDS, {featureIds: [res.features[0]?.id]})
                .then(res => {
                if (res?.data.entities) {
                  this.crownCADPlugin.command.solid.extrude({
                    sketch: res.data.entities[0]?.id,
                    height1: this.b1,
                    extrudeType1: 4
                  }, "拉伸凸台");

                  this.crownCADPlugin.command.execute().then(() => {
                    return resolve();
                  });
                } else {
                  return reject();
                }
              });
            } else {
              return reject();
            }
          });
        });
      },

      //前移前视基准面获得‘前移基准面’
      async createPlane() {
        this.crownCADPlugin.command.clearCommand();
        this.crownCADPlugin.command.datum.createPlaneByDistance({
          faceId: 8,
          paralDis: this.b1 * 0.5 + 5,
        },"前移基准面");
        await this.crownCADPlugin.command.execute();
      },

      //根据草图2绘制螺旋曲线
      async createHelixCurve() {
        //获取草图2信息
        // let res= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["草图2"]})

        let res =await this.crownCADPlugin.query.getFeaturesByNames(["草图2"])
        if (res.code=== 200 && res.data.features.length) {
          //获取草图2entityid
          // let res1= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETENTITIESBYFEATUREIDS, {featureIds: [res.features[0]?.id]})
          let res1= await this.crownCADPlugin.query.getEntitiesByFeatureIds([res.data.features[0]?.id])
          if (res1?.data.entities) {

            //绘制螺旋曲线
            this.crownCADPlugin.command.curve.createHelixCurve({
              helixPlane: res1.data.entities[0]?.id,
              inputModel: 0,
              step: this.I,
              height: this.b1 + 10,
              rotation: 0,
              isInvert: 1,
              startAngle: 90
            },'螺旋曲线')
            await this.crownCADPlugin.command.execute()

          }

        }
      },

      //绘制封闭梯形为齿形
      async createTrapezoid() {

        //获取夹角
        let j=  (0.5* (180 - 2* this.alpha) / 180) * Math.PI;

        //获取梯形的4个顶点
        let a= new Point(-1 * (this.I + 0.5 * this.b1 + 0.5 * this.px + (0.5* this.da1+ 1 - 0.5* this.d1)/Math.tan(j)),0.5* this.da1 + 1,0)

        let b= new Point(-1 * (this.I + 0.5 * this.b1 + 0.5 * this.px + (0.5* this.da1+ 1 - 0.5* this.d1)/Math.tan(j) - (0.5* this.da1+ 1 - 0.5* this.df1)/Math.tan(j)),0.5 * this.df1,0)

        let d= new Point(-1* (this.I + 0.5 * this.b1- 0.5 * this.px-  (0.5* this.da1+ 1 - 0.5* this.d1)/Math.tan(j)),0.5* this.da1+ 1,0)

        let c= new Point(-1* (this.I + 0.5 * this.b1- 0.5 * this.px-  (0.5* this.da1+ 1 - 0.5* this.d1)/Math.tan(j) + (0.5* this.da1+ 1 - 0.5* this.df1)/Math.tan(j)),0.5* this.df1,0)

        this.crownCADPlugin.command.clearCommand();
        //绘制梯形的草图3
        this.crownCADPlugin.command.sketch.createSketch({sketchName: '草图3', datumId: 22});
        //绘制梯形的4条边
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: a,
          endPoint:b
        })
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: a,
          endPoint:d
        })
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: b,
          endPoint:c
        })
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: c,
          endPoint:d
        })

        this.crownCADPlugin.command.sketch.exitSketch();
        await this.crownCADPlugin.command.execute()
        this.crownCADPlugin.command.clearCommand();
      },

      //根据齿形扫描切除
      async sweepCut() {
        //获取草图3信息
        // let res= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["草图3"]})
        let res= await this.crownCADPlugin.query.getFeaturesByNames(['草图3'])

        if (res?.data.features) {
          //获取草图3元素的id
          // let res1= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETENTITIESBYFEATUREIDS, {featureIds: [res.features[0]?.id]})
          let res1=await this.crownCADPlugin.query.getEntitiesByFeatureIds([res.data.features[0]?.id])
          //获取拉伸凸台的信息
          // let ferRes= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["拉伸凸台"]})
          let ferRes= await this.crownCADPlugin.query.getFeaturesByNames(["拉伸凸台"])
          //获取拉伸凸台的entityid
          // let ferRes1= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETENTITIESBYFEATUREIDS, {featureIds: [ferRes.features[0]?.id]})
          let ferRes1=await this.crownCADPlugin.query.getEntitiesByFeatureIds([ferRes.data.features[0]?.id])
          //获取螺旋曲线信息
          // let ferRes2= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["螺旋曲线"]})
          let ferRes2= await this.crownCADPlugin.query.getFeaturesByNames(["螺旋曲线"])
          //获取螺旋曲线的entityid
          // let ferRes3= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETENTITIESBYFEATUREIDS, {featureIds: [ferRes2.features[0]?.id]})
          let ferRes3= await this.crownCADPlugin.query.getEntitiesByFeatureIds([ferRes2.data.features[0]?.id])
          //进行扫描切除
          this.crownCADPlugin.command.solid.sweepCut({
            sweepType: 0,
            sweepProfile:res1.data.entities[0]?.id,
            sweepPath:[ferRes3.data.entities[0]?.id],
            sweepDirection: 1,
            profileDirection:2,
            cutSolids: [ferRes1.data.entities[0]?.id]
          }, "扫描切除");

          await this.crownCADPlugin.command.execute()
        }
      },
      //拉伸草图4
      createExtrude2() {
        this.crownCADPlugin.command.clearCommand();
        return new Promise((resolve, reject) => {
          //获取草图4的信息
          this.crownCADPlugin.query.getFeaturesByNames(['草图4'])
          // this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["草图4"]})
            .then(res => {
            if (res?.data.features) {
              //获取草图4的entityid
              this.crownCADPlugin.query.getEntitiesByFeatureIds([res.data.features[0]?.id])
              // this.crownCADPlugin.request.execFunction(PluginFunctionType.GETENTITIESBYFEATUREIDS, {featureIds: [res.features[0]?.id]})
                .then(res => {
                if (res?.data.entities) {
                  this.crownCADPlugin.command.solid.extrude({
                    sketch: res.data.entities[0]?.id,
                    height1: 2* this.b1,
                    extrudeType1: 4
                  }, "拉伸凸台1");

                  this.crownCADPlugin.command.execute().then(() => {
                    return resolve();
                  });
                } else {
                  return reject();
                }
              });
            } else {
              return reject();
            }
          });
        });
      },
    }
  }
</script>

<style scoped>
  >>> .el-form-item {
    margin-bottom: 0!important;
  }

  >>> .el-form-item__label {
    margin-bottom: 0!important;
  }
</style>
